#pragma once

#include <functional>
#include <sys/wait.h>
#include "Socket.hpp"

namespace TcpServerModule
{
    using namespace SocketModule;

    using tcphandler_t = std::function<bool(SockPtr, InetAddr)>;

    // 只负责IO, 不对协议进行任何处理
    class TcpServer
    {
    public:
        TcpServer(int port)
        :_listensockp(std::make_unique<TcpSocket>(port))
        ,_port(port)
        ,_isrunning(false)
        {}

        void InitServer(tcphandler_t handler)
        {
            _handler = handler;
            _listensockp->BuildTcpSocketMethod(_port);
        }

        void Loop()
        {
            _isrunning = true;
            while (_isrunning)
            {
                InetAddr clientaddr;
                SockPtr sockfd = _listensockp->Accepter(&clientaddr);
                if (sockfd == nullptr)
                    continue;

                LOG(LogLevel::INFO) << "get a new client, info is: " << clientaddr.Addr();
                pid_t id = fork();
                if (id == 0)
                {
                    _listensockp->Close();
                    if (fork() > 0) exit(0);
                    _handler(sockfd, clientaddr);
                    exit(0);
                } 
                sockfd->Close();
                waitpid(id, nullptr, 0);
            }
            _isrunning = false;
        }

        ~TcpServer()
        {
            _listensockp->Close();
        }
    private:
        std::unique_ptr<Socket> _listensockp;
        int _port;
        bool _isrunning;

        // 回调HttpServer.hpp函数获取请求处理返回响应
        tcphandler_t _handler;
    };
}